package com.tte.common.producer.test;

/**
 * 创建缓冲区
 */
public class BufferBlock {
    //定义存放食物的盒子
    private Food[] foods = new Food[10];
    //定义操作盒子的索引
    private int index;

    /**
     * 放食物
     */
    public synchronized void push(Food food) {
        //判断盒子是否已满
        while (this.index == this.foods.length) {
            try {
                //释放锁
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //唤醒领取食物的线程
        this.notify();
        this.foods[this.index] = food;
        this.index++;
    }

    /**
     * 取食物
     */
    public synchronized Food pop() {
        while (this.index == 0) {
            try {
                //满足条件后，释放锁
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //唤醒放入食物的线程
        this.notify();
        this.index--;
        return this.foods[this.index];
    }
}